var fs = require('fs')
var rp = require('request-promise')
var cheerio = require('cheerio')

var config = require('./config.js')
var util = require('./util/_default.js')
var xlsx = require('node-xlsx')

var proxyUrl = '', trycount = 10
var page=1, maxpage


var helper = util.helper

var dt = [['序号', '流水号', '药品通用名', '药品剂型', '药品规格', '包装单位', '转换系数', '批准文号', '生产企业', '中标企业', '中标价', '9省平均价', '价格确认状态', '操作']]

var dtdetail = [['药品流水号', '药品实际通用名', '实际剂型', '实际规格', '实际包装材质', '最小制剂单位', '代表品转换系数', '	最小零售包装单位', '原中标或挂网年份', '生产企业', '中标企业', '批准文号', '药品属性', '是否低价药', '是否2017甘肃医保', '报销类别', '第三方提供的省际价格详情', '第三方确认的9省价格详情', '9省价格详情', '9省平均价', '原平台', '调整后挂网交易平台及说明', '上轮价格确认状态', '中标价', '是否补充资料维护', '价格调整状态']]

var lsh = []

var href = 'http://202.100.81.115:8080/bdcp/show/drug-state-show!list.do'

function main() {

    console.log('正在抓取第' + page + '页,当前总数：' + dt.length)
    var opts = helper.deepCopy(config.reqOpts)
    opts.url = href + '?pageNo=' + page
    opts.method = 'Post'
    opts.headers.Referer = href

    rp(opts).then(function (body) {
        var $ = cheerio.load(body)
        var tr = $('tr', 'table.tablelist')
        if (tr.length > 0) {
            tr.slice(1).each(function () {
                var row = []
                row.push(
                    iGetInnerText($("td", this).eq(0).text()),
                    iGetInnerText($("td", this).eq(1).text()),
                    iGetInnerText($("td", this).eq(2).text()),
                    iGetInnerText($("td", this).eq(3).text()),
                    iGetInnerText($("td", this).eq(4).text()),
                    iGetInnerText($("td", this).eq(5).text()),
                    iGetInnerText($("td", this).eq(6).text()),
                    iGetInnerText($("td", this).eq(7).text()),
                    iGetInnerText($("td", this).eq(8).text()),
                    iGetInnerText($("td", this).eq(9).text()),
                    iGetInnerText($("td", this).eq(10).text()),
                    iGetInnerText($("td", this).eq(11).text()),
                    iGetInnerText($("td", this).eq(12).text()),
                    iGetInnerText($("td", this).eq(13).text())
                )
                lsh.push(iGetInnerText($("td", this).eq(1).text()));
                dt.push(row)
            });
            if (page % 300 == 0) {
                saveExcel(dt, page)
            }
            if (page == 1571) {
                saveExcel(dt, page)
            }
            syncdetail()
        }
    }).catch(function (err) {
        console.log(err)
        setTimeout(function () {
            main(page)
        }, Math.random() * 10 * 1000)
    })
}

function syncdetail() {
    if (lsh.length > 0) {
        GetDetail(lsh.shift())
    } else {
        page = page + 1
        main(page)
    }
}

function GetDetail(id) {
    console.log('正在抓取流水号' + id + '，当前总数：' + dtdetail.length)
    var opts = helper.deepCopy(config.reqOpts)
    opts.url = 'http://202.100.81.115:8080/bdcp/show/drug-state-show!getByFlowCode.do?flowCode=' + id
    opts.method = 'Get'
    opts.headers.Referer = 'http://202.100.81.115:8080/bdcp/new_drug_show.jsp'

    rp(opts).then(function (body) {
        var $ = cheerio.load(body)
        //console.log(body)
        var td = $('td.MyFont2')
        if (td.length > 0) {
            var row = []
            td.each(function () {
                row.push(
                    iGetInnerText($(this).text())
                )
            });
            dtdetail.push(row)
            if (dtdetail.length % 300 == 0) {
                saveDetailExcel(dtdetail, page)
            }
            if (dtdetail.length == 15702) {
                saveDetailExcel(dtdetail, page)
            } else {
                syncdetail()
            }
        }
    }).catch(function (err) {
        console.log(err)
        setTimeout(function () {
            GetDetail(id)
        }, Math.random() * 10 * 1000)
    })
}

function iGetInnerText(testStr) {
    var resultStr = testStr.replace(/\ +/g, ""); //去掉空格
    resultStr = resultStr.replace(/[ ]/g, "");    //去掉空格
    resultStr = resultStr.replace(/[\t\r\n]/g, ""); //去掉回车换行
    resultStr = resultStr.replace(/[ ]/g, "");    //去掉空格
    return resultStr;
}

function saveExcel(data, page) {
    d = (new Date()).Format('hhmmss')
    var file = xlsx.build([{ name: "mySheetName", data: data }])
    fs.writeFileSync('result_' + page + '_' + d + '.xlsx', file, 'binary')
}

function saveDetailExcel(data, page) {
    d = (new Date()).Format('hhmmss')
    var file = xlsx.build([{ name: "mySheetName", data: data }])
    fs.writeFileSync('resultDetail_' + page + '_' + d + '.xlsx', file, 'binary')
}


main()



